package com.shawn.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.telephony.PhoneStateListener;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.android.internal.telephony.ITelephony;
import com.shawn.db.dao.BlackNumDao;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BlackNumService extends Service {

    private SmsReceiver smsReceiver;
    private BlackNumDao blackNumDao;
    private TelephonyManager telephonyManager;
    private MyPhoneStateListener myPhoneStateListener;

    public BlackNumService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private class SmsReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            Object[] objects = (Object[]) intent.getExtras().get("pdus");
            for (Object obj : objects){
                SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) obj);
                String body = smsMessage.getMessageBody();
                String sender = smsMessage.getOriginatingAddress();
                int mode = blackNumDao.queryBlackNumMode(sender);
                Log.e("TAG","blaknum:"+sender);
                if(mode == BlackNumDao.SMS || mode == BlackNumDao.ALL) {
                    Log.e("TAG","blaknum");
                    abortBroadcast();
                }
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        blackNumDao = new BlackNumDao(this);
        smsReceiver = new SmsReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.setPriority(Integer.MAX_VALUE);
        intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(smsReceiver, intentFilter);


        telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        myPhoneStateListener = new MyPhoneStateListener();
        telephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

    }


    private class MyPhoneStateListener extends PhoneStateListener{

        @Override
        public void onCallStateChanged(int state, final String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            if(state == TelephonyManager.CALL_STATE_RINGING) {
                int mode = blackNumDao.queryBlackNumMode(incomingNumber);
                if(mode == BlackNumDao.ALL || mode == BlackNumDao.CALL) {
                    endCall();
                    Log.e("TAG","endcall");
                    final ContentResolver resolver = getContentResolver();
                    final Uri uri = Uri.parse("content://call_log/calls");
                    //resolver.delete(uri,"number=?",new String[]{incomingNumber});
                    resolver.registerContentObserver(uri, true, new ContentObserver(new Handler()) {
                        @Override
                        public void onChange(boolean selfChange) {
                            super.onChange(selfChange);
                            resolver.delete(uri, "number=?", new String[]{incomingNumber});
                            resolver.unregisterContentObserver(this);
                        }
                    });
                }
            }
        }

    }

    private void endCall() {
        try {
            Class loadClass = Class.forName("android.os.ServiceManager");
            //Class loadClass = BlackNumService.class.getClassLoader().loadClass("android.os.ServiceManager");
            Method method = loadClass.getMethod("getService", String.class);
            IBinder iBinder = (IBinder) method.invoke(null, Context.TELEPHONY_SERVICE);
            ITelephony iTelephony = ITelephony.Stub.asInterface(iBinder);
            iTelephony.endCall();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(smsReceiver);
        telephonyManager.listen(myPhoneStateListener,PhoneStateListener.LISTEN_NONE);
    }
}
